<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\care;


use app\dao\care\ServiceUserExtractDao;
use app\model\care\ServiceOrder;
use app\model\care\ServiceUser;
use app\model\care\ServiceUserExtract;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\FormBuilder as Form;
use think\exception\ValidateException;
use think\facade\Route as Url;

class ServiceUserExtractServices extends BaseServices
{
    public function __construct(ServiceUserExtractDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 提现申请
     * @param int $service_user_id
     * @param array $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function serviceUserExtract(int $service_user_id, array $data){
        $user = ServiceUser::find($service_user_id);
        $user = $user ? $user->toArray() : [];
        if(!$user) throw new ValidateException('未查询到人员信息');
        // 佣金总额
        $total_price = number_format(ServiceOrder::where(['is_del'=>0,'service_user_id'=>$service_user_id,'status'=>30])->sum('cost_price'),2);
        // 已提现金额
        $withdraw_price = number_format(ServiceUserExtract::where(['service_user_id'=>$service_user_id,'status'=>1])->sum('extract_price'),2);
        // 冻结中的金额
        $freeze_price = number_format(ServiceUserExtract::where(['service_user_id'=>$service_user_id,'status'=>0])->sum('extract_price'),2);
        // 可提现金额
        $usable_price = bcsub($total_price,bcadd($withdraw_price,$freeze_price,2),2);
        if ($data['money'] > $usable_price) throw new ValidateException('可提现佣金不足');
        // 最小提现金额
        $userExtractMinPrice = sys_config('user_extract_min_price');
        if ($data['money'] < $userExtractMinPrice) throw new ValidateException(400662, ['money' => $userExtractMinPrice]);
        if ($data['money'] <= 0) throw new ValidateException('提现佣金不能小于0');
        $insertData = [
            'service_user_id' => $service_user_id,
            'extract_type' => $data['extract_type'],
            'extract_price' => $data['money'],
            'add_time' => time(),
            'balance' => '',
            'status' => 0
        ];
        if(isset($data['name'])&&strlen(trim($data['name']))) {
            $insertData['real_name'] = $data['name'];
        } else {
            $insertData['real_name'] = $user['name'];
        }
        if (isset($data['cardnum'])){
            $insertData['bank_code'] = $data['cardnum'];
        } else {
            $insertData['bank_code'] = '';
        }
        if (isset($data['bankname'])) {
            $insertData['bank_address'] = $data['bankname'];
        } else {
            $insertData['bank_address'] = '';
        }
        if (isset($data['weixin'])) {
            $insertData['wechat'] = $data['weixin'];
        } else {
            $insertData['wechat'] = $user['name'];
        }
        if ($data['extract_type'] == 'alipay') {
            $insertData['alipay_code'] = $data['alipay_code'];
            $insertData['qrcode_url'] = $data['qrcode_url'];
        } else if ($data['extract_type'] == 'weixin') {
            $insertData['qrcode_url'] = $data['qrcode_url'];
        }
        $res = $this->dao->save($insertData);
        if(!$res) throw new ValidateException('提现申请失败');
        return '提现申请成功';
    }

    /**
     * 显示资源列表
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where){
        $list = $this->getServiceUserExtractList($where);
        // 佣金总额
        $extract_statistics['brokerage_count'] = number_format(ServiceOrder::where(['is_del'=>0,'status'=>30])->sum('cost_price'),2);
        //待提现金额
        $where['status'] = 0;
        $extract_statistics['price'] = $this->getExtractSum($where);
        //已提现金额
        $where['status'] = 1;
        $extract_statistics['priced'] = $this->getExtractSum($where);
        //未提现金额
        $extract_statistics['brokerage_not'] = $extract_statistics['brokerage_count'] > $extract_statistics['priced'] ? bcsub($extract_statistics['brokerage_count'], $extract_statistics['priced'], 2) : 0.00;
        return compact( 'extract_statistics','list');
    }

    /**
     * 获取提现列表
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getServiceUserExtractList(array $where){
        [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getExtractList($where, $page, $limit);
        foreach ($list['list'] as &$item) {
            $item['name'] = $item['name'] ?? '';
            $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
        }
        return $list;
    }

    /**
     * 提现金额
     * @param array $where
     * @return float
     */
    public function getExtractSum(array $where){
        return $this->dao->getExtractMoneyByWhere($where);
    }

    /**
     * 显示资源编辑表单
     * @param int $id
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(int $id){
        $UserExtract = $this->dao->get($id);
        if (!$UserExtract) throw new AdminException('数据不存在');
        $field = [];
        $field[] = Form::input('real_name', '服务人员姓名', $UserExtract['real_name']);
        $field[] = Form::number('extract_price', '提现金额', (float)$UserExtract['extract_price'])->precision(2)->disabled(true);
        if ($UserExtract['extract_type'] == 'alipay') {
            $field[] = Form::input('alipay_code', '支付宝账号', $UserExtract['alipay_code']);
        } else if ($UserExtract['extract_type'] == 'weixin') {
            $field[] = Form::input('wechat', '微信号', $UserExtract['wechat']);
        } else {
            $field[] = Form::input('bank_code', '银行卡号', $UserExtract['bank_code']);
            $field[] = Form::input('bank_address', '开户行', $UserExtract['bank_address']);
        }
        $field[] = Form::input('mark', '备注', $UserExtract['mark'])->type('textarea');
        return create_form('编辑', $field, Url::buildUrl('/care/extract/' . $id), 'PUT');
    }

    /**
     * 保存更新的资源
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function update(int $id, array $data){
        if (!$this->dao->update($id, $data)) throw new AdminException('修改失败');
        return true;
    }

    /**
     * 拒绝
     * @param int $id
     * @param string $message
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refuse(int $id, string $message){
        $extract = $this->dao->get($id);
        if (!$extract) throw new AdminException('数据不存在');
        if ($extract['status'] == 1) throw new AdminException('已经提现');
        if ($extract['status'] == -1) throw new AdminException('提现申请已被拒绝');
        $update = [
            'fail_msg' => $message,
            'fail_time' => time(),
            'status' => -1
        ];
        $res = $this->dao->update($id,$update);
        if (!$res) throw new AdminException('操作失败');
        return true;
    }

    /**
     * 通过
     * @param int $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function adopt(int $id){
        $extract = $this->dao->get($id);
        if (!$extract) throw new AdminException('数据不存在');
        if ($extract['status'] == 1) throw new AdminException('已经提现');
        if ($extract['status'] == -1) throw new AdminException('提现申请已被拒绝');
        if (!$this->dao->update($id,['status'=>1])) throw new AdminException('操作失败');
        return true;
    }

    /**
     * 提现记录
     * @param $service_user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function withdrawalRecord($service_user_id){
        $where = [];
        $where['status'] = '';
        $where['service_user_id'] = $service_user_id;
        [$page,$limit] = $this->getPageValue();
        $where['type'] = ['extract','extract_money','extract_fail'];
        $list = $this->dao->getExtractList($where,$page,$limit);
        if($list['list']){
            foreach ($list['list'] as &$item){
                $item['time'] = $item['time_key'] = $item['add_time'] ? date('Y-m', (int)$item['add_time']) : '';
                $item['add_time'] = $item['add_time'] ? date('Y-m-d H:i', (int)$item['add_time']) : '';
            }
            $times = array_merge(array_unique(array_column($list['list'], 'time_key')));
        }
        $list['time'] = $times ?? [];
        return $list;
    }
}
